package cn.kgc.listener.sms;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 */
@Configuration
public class SmsRabbitConfig {
    @Value("${mq.deadLetterExchangeName}")
    private String deadLetterExchangeName;
    @Value("${mq.deadLetterRoutingKey}")
    private String deadLetterRoutingKey;
    @Value("${mq.enableHandleDlx}")
    private boolean enableHandleDlx;

    @Bean
    public Queue clientQueue() {
        Map<String, Object> map = new HashMap<>();
        if (enableHandleDlx) {
            map.put("x-message-ttl", 60000);
            map.put("x-dead-letter-exchange", deadLetterExchangeName);
            map.put("x-dead-letter-routing-key", deadLetterRoutingKey);
            return new Queue("smsMessageQueue", true, false, false, map);
        }
        return new Queue("smsMessageQueue", true, false, false);
    }

    @Bean
    public DirectExchange directExchange(){
        return new DirectExchange("smsMessageExchange",true,false);
    }

    @Bean
    public Binding directBinding(){
        return BindingBuilder.bind(clientQueue()).to(directExchange()).with("smsMessageRoutingKey");
    }

    @Bean
    public SimpleMessageListenerContainer simpleMessageListenerContainer2(
            ConnectionFactory connectionFactory,
            SmsMessageListener smsMessageListener
    ){
        //设置连接工厂
        SimpleMessageListenerContainer simpleMessageListenerContainer=
                new SimpleMessageListenerContainer(connectionFactory);
        //设置处理消息的业务类型
        simpleMessageListenerContainer.setMessageListener(smsMessageListener);
        //信息手动确认信息
        simpleMessageListenerContainer.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        //添加需要监听的队列
        simpleMessageListenerContainer.setExposeListenerChannel(true);
        simpleMessageListenerContainer.setQueueNames("smsMessageQueue");
        return simpleMessageListenerContainer;
    }
}